package com.taikang.hmp.hbusiness.diabetes.measure.sugar.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.taikang.hmp.frame.common.TKException;
import com.taikang.hmp.frame.common.datastructre.Dto;
import com.taikang.hmp.frame.common.datastructre.support.BaseDto;
import com.taikang.hmp.frame.common.service.impl.BaseServiceImpl;
import com.taikang.hmp.frame.common.tools.DateTimeUtils;
import com.taikang.hmp.hbusiness.diabetes.measure.sugar.bean.Sugar;
import com.taikang.hmp.hbusiness.diabetes.measure.sugar.bean.SugarPlan;
import com.taikang.hmp.hbusiness.diabetes.measure.sugar.bean.SugarRecord;
import com.taikang.hmp.hbusiness.diabetes.measure.sugar.service.ISugarService;
import com.taikang.hmp.hbusiness.diabetes.measure.sugar.service.SugarUtil;

/**
 * sugar implement author:qrp time:2015年7月24日 上午10:23:59
 */
public class SugarServiceImpl extends BaseServiceImpl implements ISugarService {

	private static Logger logger = LoggerFactory.getLogger(SugarServiceImpl.class);
	
	public void saveSugarPlan(Dto dto){
		SugarPlan sp = new SugarPlan();
		//
		sp.setSource_cd(dto.getAsString("requestsource"));
		sp.setOperater(dto.getAsString("uid"));
		//
		sp.setCustomer_id(dto.getAsString("customerid"));
		sp.setDate(dto.getAsString("date"));
		String timespan = dto.getAsString("timespan");
		String Value = dto.getAsString("value");

		//设置具体的值
		if (timespan.equals("0")) {
			sp.setBreakfast_pre(Value);
		} else if (timespan.equals("1")) {
			sp.setBreakfast_aft(Value);
		} else if (timespan.equals("2")) {
			sp.setLunch_pre(Value);
		} else if (timespan.equals("3")) {
			sp.setLunch_aft(Value);
		} else if (timespan.equals("4")) {
			sp.setDinner_pre(Value);
		} else if (timespan.equals("5")) {
			sp.setDinner_aft(Value);
		} else if (timespan.equals("6")) {
			sp.setSleep_pre(Value);
		}
		insertOrUpdateSugarPlan(sp);
	}

	/**
	 * 插入或者更新计划
	 * 只保存本周内的计划
	 */
	public void insertOrUpdateSugarPlan(SugarPlan sugarPlan){
		if(sugarPlan == null){
			return;
		}
		//业务主键
		String customerid = sugarPlan.getCustomer_id();
		String date = sugarPlan.getDate();
		if(StringUtils.isEmpty(customerid) || StringUtils.isEmpty(date) ){
			throw new TKException("customerid or date must not be null");
		}
		
		//先查找
		Dto findDto = new BaseDto();
		findDto.put("customerid", customerid);
		String plandate = DateTimeUtils.getRelativeMonday(date) + "~" + DateTimeUtils.getRelativeSunday(date);
		findDto.put("plandate", plandate);
		findDto.put("date"    , date);
		SugarPlan sugarPlanInDb = (SugarPlan)super.getNewDao().queryForObject("sugar_space.getSugarPlanByOne", findDto);
		
		//如果存在
		String plan_id = null;
		if(sugarPlanInDb != null){
			plan_id = sugarPlanInDb.getPlan_id();
			sugarPlan.setPlan_id(plan_id);
			sugarPlan.setPlandate(plandate);
			//如果存在已有的血糖计划，只需要更新部分字段即可；
			super.getNewDao().update("sugar_space.update_sugarPlan", sugarPlan);
		}else{
			plan_id = java.util.UUID.randomUUID().toString();
			sugarPlan.setPlan_id(plan_id);
			sugarPlan.setPlandate(plandate);
			
			// 初始化个时间段为未设置
			if(StringUtils.isEmpty(sugarPlan.getBreakfast_pre())){
				sugarPlan.setBreakfast_pre("0");
			}
			if(StringUtils.isEmpty(sugarPlan.getBreakfast_aft())){
				sugarPlan.setBreakfast_aft("0");
			}
			if(StringUtils.isEmpty(sugarPlan.getLunch_pre())){
				sugarPlan.setLunch_pre("0");
			}
			if(StringUtils.isEmpty(sugarPlan.getLunch_aft())){
				sugarPlan.setLunch_aft("0");
			}
			if(StringUtils.isEmpty(sugarPlan.getDinner_pre())){
				sugarPlan.setDinner_pre("0");
			}
			if(StringUtils.isEmpty(sugarPlan.getDinner_aft())){
				sugarPlan.setDinner_aft("0");
			}
			if(StringUtils.isEmpty(sugarPlan.getSleep_pre())){
				sugarPlan.setSleep_pre("0");
			}
			super.getNewDao().insert("sugar_space.insert_sugarplan", sugarPlan);
		}
	}
	
	
	
	public int getPlanSugarCount(Dto dto) {
		Map<String, String> map = new HashMap<String, String>();
		logger.info("customerid: "+dto.getAsString("customerid"));
		map.put("customerid", dto.getAsString("customerid"));
		logger.info("start_date: "+dto.getAsString("startdate"));
		map.put("start_date", dto.getAsString("startdate"));
		logger.info("end_date: "+dto.getAsString("enddate"));
		map.put("end_date", dto.getAsString("enddate"));
		return (Integer)super.getNewDao().queryForObject("sugar_space.getPlanSugarCount", map);
	}

	
	
	public List<Dto> getSugarPlan(Dto dto) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("customerid", dto.getAsString("customerid"));
		map.put("start_date", dto.getAsString("startdate"));
		map.put("end_date", dto.getAsString("enddate"));
		List<SugarPlan> info = super.getNewDao().queryForList("sugar_space.getSugarPlan", map);
		List<Dto> results = new ArrayList<Dto>();
		if (info!=null && info.size() > 0) {
			for (int i = 0; i < info.size(); i++) {
				Dto result = new BaseDto();
				result.put("date", info.get(i).getDate());
				result.put("breakfastpre", info.get(i).getBreakfast_pre());
				result.put("breakfastaft", info.get(i).getBreakfast_aft());
				result.put("lunchpre", info.get(i).getLunch_pre());
				result.put("lunchaft", info.get(i).getLunch_aft());
				result.put("dinnerpre", info.get(i).getDinner_pre());
				result.put("dinneraft", info.get(i).getDinner_aft());
				result.put("sleeppre", info.get(i).getSleep_pre());
				results.add(result);
			}
		}
		return results;
	}

	
	
	public String saveSugar(Dto dto)  {	
		Sugar sugar = new Sugar();
		sugar.setSource_cd(dto.getAsString("requestsource"));
		sugar.setOperater(dto.getAsString("uid"));
		logger.info("customerid: "+dto.getAsString("customerid"));
		sugar.setCustomer_id(dto.getAsString("customerid"));
		logger.info("date: "+dto.getAsString("date"));
		// 执行时间
		String date = dto.getAsString("date");
		sugar.setDate(date.substring(0, 10));
		logger.info("timespan: "+dto.getAsString("timespan"));		
		String Timespan = dto.getAsString("timespan");
		
		logger.info("value: "+dto.getAsString("value"));
		String Value = dto.getAsString("value");
		sugar.setTimespan_cd(Timespan);
		// 是否已有数据
		List<Sugar> info = super.getNewDao().queryForList("sugar_space.getsugar", sugar);
		if (info.size() > 0) {
			logger.info("update record_id: "+info.get(0).getRecord_id());
			sugar.setRecord_id(info.get(0).getRecord_id());
			sugar.setValue(Value);
			sugar.setDate(date);
			sugar.setOperate_date(new Date());	
			super.getNewDao().update("sugar_space.update_sugar", sugar);
		} else {
			String record_id = java.util.UUID.randomUUID().toString();
			logger.info("new record_id "+record_id);
			sugar.setRecord_id(record_id);
			sugar.setValue(Value);
			sugar.setDate(date);
			sugar.setOperate_date(new Date());
			super.getNewDao().insert("sugar_space.insert_sugar", sugar);
		}
		// 返回评判结果
		Integer B_A = SugarUtil.getB_A(Timespan);
		
		String sugarValue = SugarUtil.getSugarVaule(Float.parseFloat(Value),
				B_A.toString());
		logger.info("返回评判结果 sugarValue: "+sugarValue);
		logger.info("--保存血糖测量值end--");
		return sugarValue;
	}

	
	
	
	
	public List<Object> getSugarList(Dto dto) {
		logger.info("--获取血糖测量值列表start--");
		Map<String, String> map = new HashMap<String, String>();
		
		logger.info("customerid: "+dto.getAsString("customerid"));
		map.put("customerid", dto.getAsString("customerid"));
		String start_date = "";
		logger.info("start_date: "+dto.getAsString("startdate"));
		if(!dto.getAsString("startdate").equals("")){
			start_date = dto.getAsString("startdate") + " 00:00";
		}else {
			start_date = "1900-01-01 00:00";
		}
		map.put("start_date", start_date);
		String end_date = "";
		logger.info("end_date: "+dto.getAsString("enddate"));
		if(!dto.getAsString("enddate").equals("")){			
			end_date = dto.getAsString("enddate") + " 23:59";
		}
		map.put("end_date", end_date);
		List<Sugar> info = super.getNewDao().queryForList("sugar_space.getSugarList", map);
		List<SugarPlan> info1 = super.getNewDao().queryForList("sugar_space.getSugarPlanList", map);
		List<Object> result = new ArrayList<Object>();
		for (int i = 0; i < info.size(); i++) {
			Dto  result_map = new BaseDto();			
			result_map.put("date", info.get(i).getDate());
			result_map.put("timespan", info.get(i).getTimespan_cd());
			result_map.put("value", info.get(i).getValue());
			// 是否按计划测量
			String isPlan = "0";
			for (int j = 0; j < info1.size(); j++) {
				if (info.get(i).getTimespan_cd().equals("0")) {
					isPlan = info1.get(0).getBreakfast_pre();
				} else if (info.get(i).getTimespan_cd().equals("1")) {
					isPlan = info1.get(0).getBreakfast_aft();
				} else if (info.get(i).getTimespan_cd().equals("2")) {
					isPlan = info1.get(0).getLunch_pre();
				} else if (info.get(i).getTimespan_cd().equals("3")) {
					isPlan = info1.get(0).getLunch_aft();
				} else if (info.get(i).getTimespan_cd().equals("4")) {
					isPlan = info1.get(0).getDinner_pre();
				} else if (info.get(i).getTimespan_cd().equals("5")) {
					isPlan = info1.get(0).getDinner_aft();
				} else if (info.get(i).getTimespan_cd().equals("6")) {
					isPlan = info1.get(0).getSleep_pre();
				}
			}
			result_map.put("isplan", isPlan);
			result.add(result_map);
		}
		return result;
	}

	
	@Override
	public List<SugarRecord> getSugarChart(Dto dto)  {
		SugarRecord sugarRecord = new SugarRecord();
		sugarRecord.setCustomer_id(dto.getAsString("customerid"));
		if ("1".equals(dto.getAsString("day"))) {
			sugarRecord.setDates(dto.getAsString("date"));
		} else {
			sugarRecord.setBef_date(dto.getAsString("befdate") + " 00:00");
			sugarRecord.setAft_date(dto.getAsString("aftdate") + " 23:59");
		}
		// TODO Auto-generated method stub
		return super.getNewDao().queryForList("sugar_space.getSugarChart", sugarRecord);
	}
	@Override
	public List<SugarRecord> getSugarFirst(Dto dto)  {
		SugarRecord sugarRecord = new SugarRecord();
		sugarRecord.setCustomer_id(dto.getAsString("customerid"));
		if ("1".equals(dto.getAsString("day"))) {
			sugarRecord.setDates(dto.getAsString("date"));
		} else {
			sugarRecord.setBef_date(dto.getAsString("befdate") + " 00:00");
			sugarRecord.setAft_date(dto.getAsString("aftdate") + " 23:59");
		}
		// TODO Auto-generated method stub
		return super.getNewDao().queryForList("sugar_space.getSugarFirst", sugarRecord);
	}
	@Override
	public List<SugarRecord> getSugarAfter(Dto dto)  {
		SugarRecord sugarRecord = new SugarRecord();
		sugarRecord.setCustomer_id(dto.getAsString("customerid"));
		if ("1".equals(dto.getAsString("day"))) {
			sugarRecord.setDates(dto.getAsString("date"));
		} else {
			sugarRecord.setBef_date(dto.getAsString("befdate") + " 00:00");
			sugarRecord.setAft_date(dto.getAsString("aftdate") + " 23:59");
		}
		// TODO Auto-generated method stub
		return super.getNewDao().queryForList("sugar_space.getSugarAfter", sugarRecord);
	}
	@Override
	public List<SugarRecord> getSugarSleep(Dto dto)  {
		SugarRecord sugarRecord = new SugarRecord();
		sugarRecord.setCustomer_id(dto.getAsString("customerid"));
		if ("1".equals(dto.getAsString("day"))) {
			sugarRecord.setDates(dto.getAsString("date"));
		} else {
			sugarRecord.setBef_date(dto.getAsString("befdate") + " 00:00");
			sugarRecord.setAft_date(dto.getAsString("aftdate") + " 23:59");
		}
		// TODO Auto-generated method stub
		return super.getNewDao().queryForList("sugar_space.getSugarSleep", sugarRecord);
	}

	@Override
	public List<SugarRecord> getSugarTable(Dto dto)  {
		// TODO Auto-generated method stub
		List<SugarRecord> resultList = new ArrayList();
		List<SugarRecord> times = new ArrayList();
		SugarRecord sugarRecord = new SugarRecord();
		sugarRecord.setCustomer_id(dto.getAsString("customerid"));
		if ("1".equals(dto.getAsString("day"))) {
			sugarRecord.setDates(dto.getAsString("date"));
		} else {
			sugarRecord.setBef_date(dto.getAsString("befdate") + " 00:00");
			sugarRecord.setAft_date(dto.getAsString("aftdate") + " 23:59");
		}
		times = super.getNewDao().queryForList("sugar_space.getSugarTable", sugarRecord);
		if (times == null) {
			return null;
		} else {
			SugarRecord sugarRecordResult = new SugarRecord();
			for (int i = 0; i < times.size(); i++) {
				String j = times.get(i).getTimespan_cd();
				boolean flag= false;
				if(i > 0){
					flag = times.get(i).getDates().substring(0, 10).equals(times.get(i-1).getDates().substring(0, 10));
					if(!flag){
						resultList.add(sugarRecordResult);
						sugarRecordResult = new SugarRecord();
					}
				}
				sugarRecordResult.setDates(times.get(i).getDates().substring(0, 10));
					if ("0".equals(j)) {
						if (sugarRecordResult.getBreakfast_pre() == null) {
							sugarRecordResult.setBreakfast_pre(times.get(i).getValue());
						}
					} else if ("1".equals(j)) {
						if (sugarRecordResult.getBreakfast_aft() == null) {
							sugarRecordResult.setBreakfast_aft(times.get(i).getValue());
						}
					} else if ("2".equals(j)) {
						if (sugarRecordResult.getLunch_pre() == null) {
							sugarRecordResult.setLunch_pre(times.get(i).getValue());
						}
					} else if ("3".equals(j)) {
						if (sugarRecordResult.getLunch_aft() == null) {
							sugarRecordResult.setLunch_aft(times.get(i).getValue());
						}
					} else if ("4".equals(j)){
						if (sugarRecordResult.getDinner_pre() == null) {
							sugarRecordResult.setDinner_pre(times.get(i).getValue());
						}
					} else if ("5".equals(j)){
						if (sugarRecordResult.getDinner_aft() == null) {
							sugarRecordResult.setDinner_aft(times.get(i).getValue());
						}
					} else if ("6".equals(j)) {
						if (sugarRecordResult.getSleep_pre() == null) {
							sugarRecordResult.setSleep_pre(times.get(i).getValue());
						}
					}
					if(i == times.size()-1){
							resultList.add(sugarRecordResult);
					}
			}
		}
		return resultList;
	}

	public String delSugar(Dto paramDto) {
		String temp = paramDto.getAsString("record_id");
		String[] record_ids = temp.split(",");
		for(int i = 0 ;i<record_ids.length;i++){
			super.getNewDao().delete("sugar_space.delSugar", record_ids[i]);
		}
		return "success";
	}

	public String getUserType(String uid) {
		Dto info = (Dto)super.getNewDao().queryForObject("sugar_space.getUserType", uid);
		String type = "";
		if(info != null){
			type = info.getAsString("user_type");
		}
		return type;
	}

	public List<Object> getSugarListDoctor(Dto dto) {
		logger.info("--获取血糖测量值列表start--");
		Map<String, String> map = new HashMap<String, String>();
		
		logger.info("customerid: "+dto.getAsString("customerid"));
		map.put("customerid", dto.getAsString("customerid"));
		String start_date = dto.getAsString("startdate");
		map.put("start_date", start_date);
		String end_date = dto.getAsString("enddate");
		map.put("end_date", end_date);
		List<Sugar> info = super.getNewDao().queryForList("sugar_space.getSugarListDoctor1", map);
		List<Object> result = new ArrayList<Object>();
		for (int i = 0; i < info.size(); i++) {
			Dto  result_map = new BaseDto();
			result_map.put("record_id", info.get(i).getRecord_id());
			result_map.put("date", info.get(i).getDate());
			result_map.put("timespan", info.get(i).getTimespan_cd());
			result_map.put("value", info.get(i).getValue());
			result.add(result_map);
		}
		return result;
	}

}
